<?php
/**
 * Created by PhpStorm.
 * User: xiangfeng
 * Date: 2022/4/9
 * Time: 4:02 PM
 */

namespace app\api\service;


use app\api\http\exceptions\ApiErr;
use app\api\http\exceptions\ApiExceptions;
use app\api\model\ArticleModel;
use app\api\model\NewsModel;
use think\Service;

class ArticleService extends Service
{
    /**
     * 获取文章列表（校友活动）
     * @param array $page_config
     * @param array $where
     * @return \think\Paginator
     * @throws \think\db\exception\DbException
     */
    public static function getArticleList(array $page_config, array $where = [])
    {
        $field = 'id,title,describes,image,create_time,type,image_list,other_url';
        $where = array_reverse(array_merge($where, ['status' => 1, 'delete_time' => 0]));
        $data = ArticleModel::mk()->where($where)->order('sorts desc,id desc')->field($field)->paginate($page_config)->each(function ($item) {
            $item['publish_date'] = date('Y-m-d', strtotime($item['create_time']));
            $item['image_list'] = !empty($item['image_list']) ? json_decode($item['image_list'], true) : [];
            unset($item['create_time']);
            return $item;
        });
        return $data;
    }

    /**
     * 资讯活动（公众号文章）
     * @param array $page_config
     * @param array $where
     * @return \think\Paginator
     * @throws \think\db\exception\DbException
     */
    public static function getNewsList(array $page_config, array $where = [])
    {
        $field = 'id,title,image_list,other_url,create_time';
        $where = array_reverse(array_merge($where, ['status' => 1]));
        $data = NewsModel::mk()->where($where)->order('sorts desc,id desc')->field($field)->paginate($page_config)->each(function ($item) {
            $item['image_list'] = !empty($item['image_list']) ? json_decode($item['image_list'], true) : '';
            $item['publish_date'] = date('Y-m-d', strtotime($item['create_time']));
            unset($item['create_time']);
            return $item;
        });
        return $data;
    }

    /**
     *  文章详情
     * @param int $article_id 文章ID
     * @return array
     * @throws ApiExceptions
     */
    public static function getArticleInfo(int $article_id): array
    {
        $field = 'id,title,content,create_time as publish_date,browse_num+virtual_browse_num as browse_num';
        $where = [
            'id' => $article_id,
            'status' => 1,
            'delete_time' => 0
        ];
        $data = ArticleModel::mk()->where($where)->field($field)->findOrEmpty();
        if ($data->isEmpty()) throw new ApiExceptions(ApiErr::ARTICLE_INFO_NO_EXIST);
        $data['publish_date'] = date('Y-m-d', $data['publish_date']);
        return $data->hidden(['create_time', 'delete_time', 'update_time'])->toArray();
    }
}